<script setup lang="ts">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { Dialog } from '@/components/Dialog'
import { ElButton } from 'element-plus'
import { Table } from '@/components/Table'
import { useTable } from '@/hooks/web/useTable'
import { ViewData } from '@/api/types/userType'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { ref, unref, reactive } from 'vue'
import Edit from './components/Edit.vue'
import Detail from './components/Detail.vue'
import Classes from './components/Classes.vue'
import api from '@/api'
defineOptions({
    name: 'classList'
})
const { addOrganization, modifyOrganization, deleteOrganization, getOrganizations, getOrgTypes } = api
const { register, tableObject, methods } = useTable<ViewData>({
    getListApi: getOrganizations,
    delListApi: (param) => {
        return deleteOrganization({ ids: param })
    },
    response: {
        list: 'content',
        total: 'totalElements'
    }
})
const { getList, setSearchParams } = methods
const typeList = ref([]);
const crudSchemas = reactive<CrudSchema[]>([
    {
        field: 'index', label: '序号', type: 'index',
        form: { show: false }, detail: { show: false }
    }, {
        label: "基础信息",
        form: {
            component: "Divider",
        }
    },
    {
        field: 'usci', label: '统一信用代码',
        search: { show: true },
        table: { show: false },
        form: { colProps: { span: 12 } },
        detail: { span: 2, width: 100 }
    },
    {
        field: 'usciImage', label: '营业执照',
        form: { colProps: { span: 12 } },
        table: { show: false },
        detail: { span: 2, width: 100 }
    }, {
        field: 'name', label: '门店名称',
        search: { show: true },
        width: "150px",
        form: { colProps: { span: 12 } },
        detail: { span: 2, width: 100 }
    }, {
        field: "city", label: "所在城市",
        width: "100px",
        form: {
            colProps: { span: 12 },
        },
    }
    , {
        field: "address", label: "门店地址",
        form: {
            colProps: { span: 12 },
        },
        width: "150px",
    }
    , {
        field: 'manager', label: '负责人姓名',
        search: { show: true },
        form: { colProps: { span: 12 } },
        width: "100px",
        detail: { span: 2, width: 100 }

    }, {
        field: 'managerPhone', label: '负责人手机(账户)',
        form: { colProps: { span: 12 } },
        width: "140px",
        detail: { span: 2, width: 100 }
    },
    {
        field: 'managerCard', label: '负责人身份证',
        table: { show: false },
        form: { colProps: { span: 12 } },
        detail: { span: 2, width: 100 }
    }, {
        field: "serviceType",
        label: '服务类型',
        width: "100px",
        formatter: (_, __, value: any) => {
            return value == "time" ? "按时间" : "按次数"
        },
        form: {
            component: 'Select',
            componentProps: {
                options: [
                    { label: '按时间', value: 'time' },
                    { label: '按次数', value: 'frequency' },
                ]
            }
        }
    }, {
        field: 'testNumber', label: '评测次数',
        table: { show: false },
        form: {
            colProps: { span: 12 },
            component: 'InputNumber',
        },

    }, {
        field: 'courseNumber', label: '排课次数',
        table: { show: false },
        form: {
            colProps: { span: 12 },
            component: 'InputNumber',
        },

    },
    {
        field: 'deviceCount', label: '终端个数',
        table: { show: false },
        form: {
            colProps: { span: 12 },
            component: 'InputNumber',
        },
        detail: { span: 2, width: 100 }
    }, {
        field: 'expireDate', label: '有效期',
        table: { show: false },
        form: {
            colProps: { span: 12 },
            component: 'DatePicker',
            componentProps: {
                type: 'date',
                valueFormat: 'YYYY-MM-DD'
            }
        },
        detail: { span: 2, width: 100 }
    }, {
        field: 'status', label: '状态',
        width: "80px",
        form: {
            colProps: { span: 12 },
            component: 'Select',
            componentProps: {
                options: [
                    { label: '启用', value: '启用' },
                    { label: '禁用', value: '禁用' }
                ]
            }
        },
        detail: { span: 2, width: 100 }
    }, {
        field: "typeName", label: "类型",
        width: "125px",
        form: { show: false },
    }, {
        field: "typeId", label: "类型",
        table: { show: false },
        form: {
            component: "TreeSelect",
            componentProps: {
                data: typeList,
                props: { label: 'name', value: 'id' },
                checkStrictly: true,
                renderAfterExpand: false
            },
        }
    },
    {
        label: "应用权限",
        form: {
            component: "Divider",
        }
    },
    {
        field: 'apps', label: '',
        form: {
            colProps: { span: 24 }, 
            // component: "Checkbox", 
            // componentProps: {
            //     options: [
            //         { label: '评测老师管理', value: '1' },
            //         { label: '感统评测', value: '2' },
                    
            //     ]
            // }
        },
        table: { show: false },
        detail: { show: false }
    },

    {
        field: 'action',
        fixed: 'right',
        width: '390px',
        label: '操作',
        form: { show: false },
        detail: { show: false }

    }
])

const { allSchemas } = useCrudSchemas(crudSchemas)
const dialogVisible = ref(false)
const deviceVisible = ref(false)
const classesVisible = ref(false)
const dialogTitle = ref('')
const pageLoad = async () => {
    getList()
    const res = await getOrgTypes();
    typeList.value = res.data;
}
pageLoad();
const AddAction = () => {
    dialogTitle.value = '添加'
    tableObject.currentRow = null
    actionType.value = 'add'
    dialogVisible.value = true
}
const delLoading = ref(false)
const delData = async (row: ViewData | null, multiple: boolean) => {
    tableObject.currentRow = row
    const { delList, getSelections } = methods
    const selections = await getSelections()
    delLoading.value = true
    await delList(
        multiple ? selections.map((v) => v.id) : [tableObject.currentRow?.id as string],
        multiple
    ).finally(() => {
        delLoading.value = false
    })
}
const actionType = ref('')

const action = (row: ViewData, type: string) => {
    dialogTitle.value = type === 'edit' ? '编辑' : '详情'
    actionType.value = type
    tableObject.currentRow = row
    dialogVisible.value = true
}
const showDevice = (row: ViewData) => {
    tableObject.currentRow = row
    deviceVisible.value = true
}
const showClasses = (row: ViewData) => {
    tableObject.currentRow = row
    classesVisible.value = true
}
const writeRef = ref<ComponentRef<typeof Edit>>()
const loading = ref(false)

const save = async () => {
    const write = unref(writeRef)
    await write?.elFormRef?.validate(async (isValid) => {
        if (isValid) {
            loading.value = true
            const data = (await write?.getFormData()) as ViewData
            let apiReques = data.id ? modifyOrganization : addOrganization
            const res = await apiReques(data)
                .catch(() => { })
                .finally(() => {
                    loading.value = false
                })
            if (res) {
                dialogVisible.value = false
                tableObject.currentPage = 1
                getList()
            }
        }
    })
}
</script>

<template>
    <ContentWrap>
        <Search :schema="allSchemas.searchSchema" @search="setSearchParams" @reset="setSearchParams" />

        <div class="mb-10px">
            <ElButton type="primary" @click="AddAction">添加</ElButton>
            <ElButton :loading="delLoading" type="danger" @click="delData(null, true)">
                删除
            </ElButton>
        </div>
        <Table v-model:pageSize="tableObject.pageSize" v-model:currentPage="tableObject.currentPage"
            :columns="allSchemas.tableColumns" :data="tableObject.tableList" :loading="tableObject.loading" :pagination="{
                total: tableObject.total
            }" @register="register">
            <template #action="{ row }">
                <ElButton type="primary" @click="action(row, 'edit')"> 编辑 </ElButton>
                <ElButton type="danger" @click="delData(row, false)"> 删除 </ElButton>
                <ElButton type="warning" @click="showDevice(row)"> 查看设备信息 </ElButton>
                <ElButton type="info" @click="showClasses(row)"> 管理班级 </ElButton>

            </template>
        </Table>
    </ContentWrap>

    <Dialog v-model="dialogVisible" :title="dialogTitle" max-height="600px" width="1000px">
        <Edit v-if="actionType !== 'detail'" ref="writeRef" :form-schema="allSchemas.formSchema"
            :current-row="tableObject.currentRow" />
        <template #footer>
            <ElButton v-if="actionType !== 'detail'" type="primary" :loading="loading" @click="save">
                保存
            </ElButton>
            <ElButton @click="dialogVisible = false">关闭</ElButton>
        </template>
    </Dialog>
    <Dialog v-model="deviceVisible" title="设备信息" max-height="420px" width="800px">
        <Detail ref="writeRef" :form-schema="allSchemas.formSchema" :current-row="tableObject.currentRow" />
        <template #footer>
            <ElButton @click="deviceVisible = false">关闭</ElButton>
        </template>
    </Dialog>
    <Dialog v-model="classesVisible" title="班级管理" max-height="520px" width="980px">
        <Classes :current-row="tableObject.currentRow" />
        <template #footer>
            <ElButton @click="classesVisible = false">关闭</ElButton>
        </template>
    </Dialog>
</template>
